package com.fdmgroup.benchmarker.lib;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.fdmgroup.benchmarker.lib.common.BenchmarkReport;
import com.fdmgroup.benchmarker.lib.common.BenchmarkResult;
import com.fdmgroup.benchmarker.lib.common.BenchmarkSettings;
import com.fdmgroup.benchmarker.lib.common.utilities.BenchmarkReportUtility;
import com.fdmgroup.benchmarker.lib.common.utilities.BenchmarkResultUtility;
import com.fdmgroup.benchmarker.lib.dao.BenchmarkReportDao;
import com.fdmgroup.benchmarker.lib.thread.BenchmarkTask;
import com.fdmgroup.benchmarker.lib.thread.ThreadPool;

public class BenchmarkRunner {
	private BenchmarkSettings mSettings;

	public BenchmarkRunner(BenchmarkSettings settings) {
		mSettings = settings;
	}

	public BenchmarkResult runBenchmark() {
		ThreadPool[] pool = new ThreadPool[mSettings.getSampleSize()];
		BenchmarkResult[] results = new BenchmarkResult[mSettings.getSampleSize()];
		for (int i = 0; i < mSettings.getSampleSize(); i++) {
			pool[i] = new ThreadPool(mSettings.getPoolSize(), mSettings.getTask());
		}

		for (int i = 0; i < mSettings.getSampleSize(); i++) {
			pool[i].initializePool();
			results[i] = pool[i].startPool(100);
		}
		return BenchmarkResultUtility.mergeBenchmarkResults(results);
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		BenchmarkReportDao reportDao = (BenchmarkReportDao) context.getBean("reportDao");

		BenchmarkTask task = new BenchmarkTask(((){

			@Override
			public void performTask() {
				Math.sqrt(566423244);
			}

			@Override
			public String getDescription() {
				return "Square root of 5664232434";
			}
		};
		BenchmarkSettings settings = new BenchmarkSettings(task,1, 1, 100);
		BenchmarkRunner runner = new BenchmarkRunner(settings);
		BenchmarkResult result = runner.runBenchmark();	
		BenchmarkReport report = BenchmarkReportUtility.createBenchmarkReport(settings, result);
		reportDao.importReport(report);

		List<BenchmarkReport> reports = reportDao.getReports();
		for (BenchmarkReport r : reports) {
			System.out.println(r);
		}
		System.out.println(reports.size());
	}
}
